/**
 *Project: jh-framework
 *File: cn.xkshow.io.image.ValidateCodeHandle 
 *Author: hardy(admin@xkshow.cn) Copyright
 ****************************************************************
 *   VERSION       DATE            BY       CHANGE/COMMENT
 * --------------------------------------------------------------
 *    1.0        2013-7-11         hardy         create
 ****************************************************************
 *note:
 ***************************************************************/ 
package cn.xkshow.io.image;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.xkshow.framework.FramewConstants;

public class ValidateCodeHandle {
	private static ValidateCodeHandle instance = null;
	private final String CONTENT_TYPE = "image/jpeg";
	
	/*
	 * @param: request, response, width, height
	 */
	public BufferedImage creatImage(HttpServletRequest request, HttpServletResponse response
			,int width, int height) {

		BufferedImage image = new BufferedImage(width, height, 1);

		Graphics g = image.getGraphics();

		Random random = new Random();

		g.setColor(new Color(238, 238, 238));
		g.fillRect(0, 0, width, height);

		g.setFont(new Font("Times New Roman", 1, 16));

		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 0; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		String rand = "";
		StringBuffer sRand = new StringBuffer(4);
		for (int i = 0; i < 4; i++) {
			rand = String.valueOf(random.nextInt(10));
			sRand.append(rand);
			
			g.setColor(new Color(
						20 + random.nextInt(110)
						,20 + random.nextInt(110)
						,20 + random.nextInt(110)));
			g.drawString(rand, 10 * i + 3, 16);
		}

		g.dispose();
		
		response.setContentType(CONTENT_TYPE);
		request.getSession(true).setAttribute(FramewConstants.IMG_ValidateCode, sRand);
		
		return image;
	}
	public Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
	
	/*
	 * The constructor 
	 */
	private ValidateCodeHandle() {		
	}
	public static ValidateCodeHandle getInstance() {
		if(null == instance){
			instance = new ValidateCodeHandle();
		}
		return instance;
	}
}
